#include "Wakeup.h"
#include "RingBuffer.h"
#include "Codec.h"
#include "Model.h"

#ifdef WIN32
#define SAVE_SAMPLE
#endif

#ifdef SAVE_SAMPLE
extern void save_sample(short save[HDRCNT*BUFLEN]);
#endif

typedef int LAYERBUFFER[HDRCNT*BUFLEN];

LAYERBUFFER * m_LayerBuffer;

static short * m_WavInput = 0;
static int * m_NetInput = 0;

void WakeupInit(void)
{
	m_LayerBuffer = (LAYERBUFFER*)MALLOC(sizeof(LAYERBUFFER)*2);
	memset(m_LayerBuffer, 0, sizeof(LAYERBUFFER)*2);
	m_WavInput = (short*)m_LayerBuffer[0];
	m_NetInput = m_LayerBuffer[1];

	RingBufferInit();
	CodecInit();
	ModelInit();
}

void WakeupRelease(void)
{
	if(m_LayerBuffer)
	{
		FREE(m_LayerBuffer);
		m_LayerBuffer = 0;
	}

	m_WavInput = 0;
	m_NetInput = 0;

	RingBufferRelease();
	CodecRelease();
	ModelRelease();
}

int OnWaveData(short* data, int len/* = BUFLEN*/)	//return -1.0=null; others=hisiri confidence; 
{
	static int chunks = 0;

#ifdef SAVE_SAMPLE
	short save[HDRCNT*BUFLEN];
#endif

	assert(len == BUFLEN);

	if(m_LayerBuffer == 0)
		return -1;

	RingBufferSetWaveData(data, len);
	chunks++;

	if((chunks % 4) == 0)
	{
		RingBufferGetWaveData(m_WavInput);
#ifdef SAVE_SAMPLE
		memcpy(save, m_WavInput, sizeof(save));
#endif
		if(Encode(m_WavInput, m_NetInput))
		{
			int out;
			int ret;
			Forward(m_NetInput, &out);
			ret = Decode(&out);
			if(ret > SCALE)
			{
#ifdef SAVE_SAMPLE
				save_sample(save);
#endif
				RingBufferClear();
				return ret;
			}
		}
	}

	return -1;
}

int OnFileData(short* data, int len/* = HDRCNT*BUFLEN*/)	//return -1.0=null; others=hisiri confidence; 
{
	if(m_LayerBuffer == 0)
		return -1;

	assert(len == HDRCNT*BUFLEN);

	if(Encode(data, m_NetInput))
	{
		int out;
		Forward(m_NetInput, &out);
		return Decode(&out);
	}

	return -1;
}
